package com.taoye.thread;

/**
 * ThreadLocal的使用
 *
 * @author : Mr.Tao
 * @version : 1.0
 * @date : 2022/4/4 10:31
 **/
public class Demo48 {
    public static void main(String[] args) throws InterruptedException {
        Demo48Service service = new Demo48Service();
        Demo48ThreadA t1 = new Demo48ThreadA(service);
        Demo48ThreadB t2 = new Demo48ThreadB(service);
        t1.start();
        t2.start();
    }
}

class Demo48Service {
    private String v1;
    private ThreadLocal<String> v2 = new ThreadLocal<>();

    public String getV1() {
        return v1;
    }

    public void setV1(String v1) {
        this.v1 = v1;
    }

    public String getV2() {
        return v2.get();
    }

    public void setV2(String str) {
        v2.set(str);
    }
}

class Demo48ThreadA extends Thread {
    private Demo48Service service;

    public Demo48ThreadA(Demo48Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        try {
            service.setV1("A线程修改的V1");
            Thread.sleep(500);
            service.setV2("A线程修改的V2");
            System.out.println("A线程结果：v1=" + service.getV1() + ",v2=" + service.getV2());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Demo48ThreadB extends Thread {

    private Demo48Service service;

    public Demo48ThreadB(Demo48Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(200);
            service.setV1("B线程修改的V1");
            service.setV2("B线程修改的V2");
            System.out.println("B线程结果：v1=" + service.getV1() + ",v2=" + service.getV2());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
